const { catchAsync } = require('../utils/errorHandler');
const AppError = require('../utils/errorHandler').AppError;

// 代码执行控制器
exports.executeCode = catchAsync(async (req, res, next) => {
  const { code, context } = req.body;

  if (!code) {
    return next(new AppError('代码内容不能为空', 400));
  }

  try {
    // 这里实现代码执行逻辑
    // 注意：实际生产环境中需要使用沙箱环境执行代码
    // 当前为演示版本，返回模拟结果
    
    const executionResult = {
      success: true,
      output: '代码执行成功',
      logs: [],
      errors: [],
      executionTime: Date.now(),
      context: context || {}
    };

    // 简单的代码分析和模拟执行
    if (code.includes('create_cube')) {
      executionResult.output = '立方体创建成功';
      executionResult.logs.push('创建了一个新的立方体');
    }
    
    if (code.includes('move_object')) {
      executionResult.output += '\n物体移动完成';
      executionResult.logs.push('物体位置已更新');
    }
    
    if (code.includes('rotate_object')) {
      executionResult.output += '\n物体旋转完成';
      executionResult.logs.push('物体旋转已应用');
    }

    res.status(200).json({
      status: 'success',
      data: {
        result: executionResult
      }
    });
  } catch (error) {
    return next(new AppError('代码执行失败: ' + error.message, 500));
  }
});

// 验证代码语法
exports.validateCode = catchAsync(async (req, res, next) => {
  const { code } = req.body;

  if (!code) {
    return next(new AppError('代码内容不能为空', 400));
  }

  try {
    // 简单的语法验证
    const validationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      suggestions: []
    };

    // 基本语法检查
    if (code.includes('undefined') || code.includes('null')) {
      validationResult.warnings.push('代码中包含undefined或null值，请检查');
    }

    // 检查是否包含支持的函数
    const supportedFunctions = ['create_cube', 'move_object', 'rotate_object'];
    const hasValidFunction = supportedFunctions.some(func => code.includes(func));
    
    if (!hasValidFunction) {
      validationResult.suggestions.push('建议使用支持的3D操作函数');
    }

    res.status(200).json({
      status: 'success',
      data: {
        validation: validationResult
      }
    });
  } catch (error) {
    return next(new AppError('代码验证失败: ' + error.message, 500));
  }
});

// 获取代码执行历史
exports.getExecutionHistory = catchAsync(async (req, res, next) => {
  const userId = req.user.id;
  const { page = 1, limit = 10 } = req.query;

  // 这里应该从数据库获取执行历史
  // 当前返回模拟数据
  const mockHistory = {
    executions: [
      {
        id: '1',
        code: 'create_cube(1, "red");',
        result: '立方体创建成功',
        executedAt: new Date().toISOString(),
        executionTime: 150
      },
      {
        id: '2',
        code: 'move_object("x", 5);',
        result: '物体移动完成',
        executedAt: new Date(Date.now() - 3600000).toISOString(),
        executionTime: 80
      }
    ],
    pagination: {
      currentPage: parseInt(page),
      totalPages: 1,
      totalItems: 2,
      limit: parseInt(limit)
    }
  };

  res.status(200).json({
    status: 'success',
    data: mockHistory
  });
});

// 保存代码片段
exports.saveCodeSnippet = catchAsync(async (req, res, next) => {
  const { code, title, description, tags } = req.body;
  const userId = req.user.id;

  if (!code || !title) {
    return next(new AppError('代码和标题不能为空', 400));
  }

  // 这里应该保存到数据库
  // 当前返回模拟结果
  const savedSnippet = {
    id: Date.now().toString(),
    title,
    description: description || '',
    code,
    tags: tags || [],
    userId,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  };

  res.status(201).json({
    status: 'success',
    data: {
      snippet: savedSnippet
    }
  });
});

// 获取代码片段列表
exports.getCodeSnippets = catchAsync(async (req, res, next) => {
  const userId = req.user.id;
  const { page = 1, limit = 10, search, tags } = req.query;

  // 这里应该从数据库查询
  // 当前返回模拟数据
  const mockSnippets = {
    snippets: [
      {
        id: '1',
        title: '创建红色立方体',
        description: '创建一个红色的立方体',
        code: 'create_cube(1, "red");',
        tags: ['3d', 'cube'],
        createdAt: new Date().toISOString()
      },
      {
        id: '2',
        title: '物体移动动画',
        description: '让物体沿X轴移动',
        code: 'move_object("x", 5);',
        tags: ['animation', 'movement'],
        createdAt: new Date(Date.now() - 86400000).toISOString()
      }
    ],
    pagination: {
      currentPage: parseInt(page),
      totalPages: 1,
      totalItems: 2,
      limit: parseInt(limit)
    }
  };

  res.status(200).json({
    status: 'success',
    data: mockSnippets
  });
});